<template>
  <div style="min-width: 980px">
      <a-card>
          <h3>指令调试</h3>
          <p>调试提示:请在下方选择菜单中选择发送指令的设备</p>
          <a-select mode="multiple" placeholder="点击选择推送设备" :value="selectedItems" @change="selectHandleChange"
                  style="width: 100%">
              <a-select-option v-for="item in filteredOptions" :key="item" :value="item">
                  {{item}}
              </a-select-option>
          </a-select>
      </a-card>
        <a-card style="margin-top: 20px">
            <div style="width: 50%;float: left">
                <p style="color: #2c3e50;font-weight: bold;">模拟设备下发数据</p>
                <div style="min-height: 540px;width: 420px;border-width: 0.5px;border-style: solid;border-radius:4px;border-color: #ddd;padding: 10px;overflow: scroll">
                    <div style="min-height: 460px;">
                        <a-table :columns="columns" :dataSource="data" :pagination="false" :loading="memberLoading">
                            <template v-for="(col, i) in ['name', 'value']" :slot="col" slot-scope="text, record">
                                <a-input :key="col" v-if="record.editable" style="margin: -5px 0" :value="text"
                                         :placeholder="columns[i].title" @change="e => handleChange(e.target.value, record.key, col)"/>
                                <template v-else>{{ text }}</template>
                            </template>
                            <template slot="operation" slot-scope="text,record">
                                <template v-if="record.editable">
                          <span v-if="record.isNew">
                           <a @click="saveRow(record)">添加</a>
                           <a-divider type="vertical" />
                           <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
                             <a>删除</a>
                           </a-popconfirm>
                        </span><span v-else>
                              <a @click="saveRow(record)">保存</a>
                              <a-divider type="vertical" />
                              <a @click="cancel(record.key)">取消</a>
                            </span>
                                </template>
                                <span v-else>
                            <a @click="toggle(record.key)">编辑</a>
                            <a-divider type="vertical" />
                            <a-popconfirm title="是否要删除此行？" @confirm="remove(record.key)">
                              <a>删除</a>
                            </a-popconfirm>
                        </span>
                            </template>
                        </a-table>
                        <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" icon="plus" @click="newMember">新增数据</a-button>
                    </div>
                    <div style="width: 100%;padding: 10px;padding-left: 30%;padding-right: 30%;">
                        <a-button type="primary" shape="round" icon="cloud-upload" style="width: 100%;"
                        @click="publishData">推送</a-button>
                    </div>
                </div>
            </div>
            <div style="width: 50%;float: left;">
                <p style="color: #2c3e50;font-weight: bold;">调试日志</p>
                <div style="height: 540px;width:420px;border-style: solid;border-width: 0.5px;border-color: #dddddd;border-radius: 4px;
                     padding: 20px;overflow-scrolling: auto;overflow: scroll">
                    <div style="border-radius: 4px;margin-bottom: 10px;line-height: 10px"
                         v-for="(item,i) in list_data" :key="i">
                        <p >设备：{{item.clientid}}</p>
                        <p >数据：{{item.payload}}</p>
                        <p >时间：{{item.datetime}}</p>
                        <a-divider />
                    </div>
                    <div style="height: 60px;border-radius: 4px;margin-bottom: 10px">
                            <p>设备上线成功</p>
                        <p>时间：{{datetime}}</p>
                    </div>
                </div>
            </div>



        </a-card>


       </div>




</template>

<script>
    import  moment from 'moment'
  import {getClient,publish} from "@/api/mqtt";

  const  columns=[
        {
            title: '键值',
            dataIndex: 'name',
            key: 'name',
            width: '30%',
            scopedSlots: { customRender: 'name' }
        },
        {
            title: '内容',
            dataIndex: 'value',
            key: 'value',
            width: '40%',
            scopedSlots: { customRender: 'value' }
        },

        {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
        }
    ];

    export default {
        name: "Debug",
        data(){
            return{
                loading: false,
                memberLoading: false,
                selectedItems: [],
                columns,
                datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                size: 'large',
                data: [
                    {
                        key: '1',
                        name: 'led',
                        value: 'on',
                        editable: false,
                    },

                ],
                OPTIONS : [],
                list_data:[],

            }
        },computed: {
            filteredOptions() {
                return this.OPTIONS.filter(o => !this.selectedItems.includes(o));
            },
        },created(){
            this.getClients()
        },

        methods: {
            publishData(){
                //console.log(this.data)
                const data={}
                this.data.forEach((item)=>{
                      //data.push(item.name+':'+item.value)
                      data[item.name]=item.value
                })
                //console.log(data)
                //console.log(this.selectedItems)
                if(this.selectedItems.length==0){
                    this.$message.warning("请选择推送的设备！");
                }else{
                    this.selectedItems.forEach((item)=>{
                        console.log(item)
                        publish({ "topic": item, "payload":JSON.stringify(data), "qos": 0,"retain": false,"client_id": "admin"}).then((response)=>{
                              console.log(response.data)
                             this.list_data.push({"clientid":item,"payload":JSON.stringify(data),"time":moment(new Date()).format('YYYY-MM-DD HH:mm:ss')})

                        }).catch()
                    })
                }
            },
            getClients(){

                //console.log("4-挂载，实例被创建时执行")
                getClient().then((res)=>{
                    console.log(res.data)
                    sessionStorage.setItem('client',JSON.stringify(res.data))
                    res.data.forEach((item)=>{
                        //console.log(item["clientid"])
                        this.OPTIONS.push(item["clientid"])
                    })
                }).catch()
            },
            selectHandleChange(selectedItems) {
                this.selectedItems = selectedItems;
            },
            handleChange(value, key, column) {
                const newData = [...this.data];
                const target = newData.filter(item => key === item.key)[0];
                if (target) {
                    target[column] = value;
                    this.data = newData;
                }
            },
            newMember () {
                const length = this.data.length
                this.data.push({
                    key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
                    name: '',
                    workId: '',
                    department: '',
                    editable: true,
                    isNew: true
                })
            },
            remove (key) {
                const newData = this.data.filter(item => item.key !== key)
                this.data = newData
            },
            saveRow (record) {
                this.memberLoading = true
                const { key, name, value,  } = record
                if (!name || !value) {
                    this.memberLoading = false
                    this.$message.error('请填写完整成员信息。')
                    return
                }
                // 模拟网络请求、卡顿 800ms
                new Promise((resolve) => {
                    setTimeout(() => {
                        resolve({ loop: false })
                    }, 800)
                }).then(() => {
                    const target = this.data.find(item => item.key === key)
                    target.editable = false
                    target.isNew = false
                    this.memberLoading = false
                })
            },
            toggle (key) {
                const target = this.data.find(item => item.key === key)
                target._originalData = { ...target }
                target.editable = !target.editable
            },
            cancel (key) {
                const target = this.data.find(item => item.key === key)
                Object.keys(target).forEach(key => { target[key] = target._originalData[key] })
                target._originalData = undefined
            },

        },
    }
</script>

<style scoped>

</style>
